package com.changgou.consume.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.consume.config.RabbitMQConfig;
import com.changgou.consume.service.SecKillOrderService;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class ConsumerListener {

    @Autowired
    private SecKillOrderService secKillOrderService;


    @RabbitListener(queues = RabbitMQConfig.SECKILL_ORDER_QUEQUE)
    public void receiveSecKillOrderMessage(Message message, Channel channel){

        System.out.println("接收到了秒杀任务的消息: "+new Date());

        //设置预抓取总数
        try {
            channel.basicQos(300);
        } catch (IOException e) {
            e.printStackTrace();
        }

        SeckillOrder seckillOrder  = JSON.parseObject(message.getBody(), SeckillOrder.class);

        int result = secKillOrderService.createOrder(seckillOrder);

        if(result>0){
            //成功，返回成功的应答
            try {
                /*
                * 第一个参数：消息的唯一标识
                * 第二个参数：是否开启批处理
                * */
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            //同步mysql失败
            try {
                /*
                * 第一个参数：消息的唯一标识
                  第二个参数:true->所有消费者都拒绝这条消息； false->当前消费者拒绝
                  * 第三个参数：true->当前消息进入死信队列（也叫延迟消息队列）； false->进入原有队列头部
                * */
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}
